package ge.telasi.tasks.ui.comp;

import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;

/**
 * @author dimitri
 */
public class TableUtils {

    public static void setSelectionAtEnd(JTable tbl) {
        int rowCoount = tbl.getRowCount();
        setSelectionAt(tbl, rowCoount - 1);
    }

    public static void setSelectionAt(JTable tbl, int index) {
        tbl.getSelectionModel().setSelectionInterval(index, index);
        JViewport viewport = (JViewport) tbl.getParent();
        Rectangle rect = tbl.getCellRect(index, 0, true);
        Point pt = viewport.getViewPosition();
        rect.setLocation(rect.x - pt.x, rect.y - pt.y);
        viewport.scrollRectToVisible(rect);
    }

    public static void setSelectionAt(JTable tbl, int[] indecies) {
        ListSelectionModel model = tbl.getSelectionModel();
        model.clearSelection();
        int min = 0;
        int max = 0;
        for (int index : indecies) {
            if (index == -1) {
                continue;
            }
            if (min > index) min = index;
            if (max < index) max = index;
            model.addSelectionInterval(index, index);
        }
        JViewport viewport = (JViewport) tbl.getParent();
        Rectangle rect = tbl.getCellRect(min, 0, true);
        Point pt = viewport.getViewPosition();
        rect.setLocation(rect.x - pt.x, rect.y - pt.y);
        viewport.scrollRectToVisible(rect);
    }

}
